<script setup lang="ts">
import { defineStore } from 'pinia'

definePage({
  name: 'pinia',
  style: {
    navigationBarTitleText: 'Pinia 演示',
  },
})

const { success: showSuccess } = useGlobalToast()

// 定义一个基础的计数器store
const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)

  function increment() {
    count.value++
  }

  function decrement() {
    count.value--
  }

  function reset() {
    count.value = 0
  }

  return {
    count,
    doubleCount,
    increment,
    decrement,
    reset,
  }
})

// 定义一个用户信息store（演示持久化）
const useUserStore = defineStore('user', () => {
  const userInfo = ref({
    name: '',
    email: '',
    avatar: '',
    theme: 'light',
  })

  const isLoggedIn = computed(() => !!userInfo.value.name)

  function setUserInfo(info: Partial<typeof userInfo.value>) {
    userInfo.value = { ...userInfo.value, ...info }
  }

  function clearUserInfo() {
    userInfo.value = {
      name: '',
      email: '',
      avatar: '',
      theme: 'light',
    }
  }

  function toggleTheme() {
    userInfo.value.theme = userInfo.value.theme === 'light' ? 'dark' : 'light'
  }

  return {
    userInfo,
    isLoggedIn,
    setUserInfo,
    clearUserInfo,
    toggleTheme,
  }
})

// 定义一个临时store（不持久化）
const useTempStore = defineStore('temp', () => {
  const tempData = ref({
    message: '',
    timestamp: Date.now(),
  })

  function setMessage(msg: string) {
    tempData.value.message = msg
    tempData.value.timestamp = Date.now()
  }

  function clearMessage() {
    tempData.value.message = ''
    tempData.value.timestamp = Date.now()
  }

  return {
    tempData,
    setMessage,
    clearMessage,
  }
})

// 使用stores
const counterStore = useCounterStore()
const userStore = useUserStore()
const tempStore = useTempStore()

// 表单数据
const userForm = ref({
  name: '',
  email: '',
})

const tempMessage = ref('')

// 复制代码到剪贴板
function copyCode(code: string) {
  uni.setClipboardData({
    data: code,
    showToast: false,
    success: () => {
      uni.hideToast()
      showSuccess({ msg: '代码已复制到剪贴板' })
    },
  })
}

// 保存用户信息
function saveUserInfo() {
  if (!userForm.value.name) {
    uni.showToast({
      title: '请输入用户名',
      icon: 'none',
    })
    return
  }

  userStore.setUserInfo({
    name: userForm.value.name,
    email: userForm.value.email,
    avatar: '😆',
  })

  showSuccess({ msg: '用户信息已保存（会持久化）' })
}

// 设置临时消息
function setTempMessage() {
  if (!tempMessage.value) {
    uni.showToast({
      title: '请输入消息内容',
      icon: 'none',
    })
    return
  }

  tempStore.setMessage(tempMessage.value)
  tempMessage.value = ''
  showSuccess({ msg: '临时消息已设置（不会持久化）' })
}

// 链接导航处理
function handleNavigate(url: string) {
  // #ifdef H5
  window.open(url, '_blank')
  // #endif
  // #ifndef H5
  uni.setClipboardData({
    data: url,
    showToast: false,
    success: () => {
      uni.hideToast()
      showSuccess({ msg: `${url} 已复制到剪贴板` })
    },
  })
  // #endif
}
</script>

<template>
  <view class="page-container">
    <!-- 头部介绍 -->
    <view class="header-card">
      <view class="header-content">
        <view class="emoji">
          🍍
        </view>
        <view class="title">
          Pinia 状态管理
        </view>
        <view class="subtitle">
          Vue 3 的直观状态管理库
        </view>
        <view class="description">
          轻量、类型安全、支持组合式API
        </view>
        <view class="description">
          本项目默认持久化所有 Store 数据，开发者可以配置排除列表
        </view>
      </view>
    </view>

    <!-- 基础计数器演示 -->
    <demo-block title="基础使用 - 计数器" transparent>
      <view class="content-card">
        <view class="counter-display">
          <view class="count">
            {{ counterStore.count }}
          </view>
          <view class="double-count">
            双倍值: {{ counterStore.doubleCount }}
          </view>
        </view>

        <view class="button-grid">
          <wd-button type="success" size="small" @click="counterStore.increment">
            +1
          </wd-button>
          <wd-button type="warning" size="small" @click="counterStore.decrement">
            -1
          </wd-button>
          <wd-button type="info" size="small" @click="counterStore.reset">
            重置
          </wd-button>
        </view>

        <!-- 代码示例 -->
        <view class="code-examples">
          <view class="code-block">
            <view class="code-title">
              定义 Store:
            </view>
            <view
              class="code-content"
              @click="
                copyCode(`const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)

  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})`)
              "
            />
          </view>

          <view class="code-block">
            <view class="code-title">
              使用 Store:
            </view>
            <view
              class="code-content"
              @click="
                copyCode(`const counterStore = useCounterStore()
// 直接使用
counterStore.increment()
// 响应式访问
console.log(counterStore.count)`)
              "
            >
              <text>const counterStore = useCounterStore()</text>
              <text>counterStore.increment() // 调用方法</text>
              <text>console.log(counterStore.count) // 访问状态</text>
            </view>
          </view>
        </view>
      </view>
    </demo-block>

    <!-- 用户信息演示（持久化） -->
    <demo-block title="持久化演示 - 用户信息" transparent>
      <view class="info-box success">
        <view class="info-title">
          ✅ 持久化存储
        </view>
        <view class="info-body">
          这个 Store 的数据会自动保存到本地存储，刷新页面后数据不会丢失
        </view>
      </view>

      <view class="user-info-container">
        <!-- 当前用户信息 -->
        <view class="content-card">
          <view class="card-title">
            当前用户信息
          </view>

          <view v-if="userStore.isLoggedIn" class="user-info">
            <view class="avatar">
              {{ userStore.userInfo.avatar }}
            </view>
            <view class="user-details">
              <view class="user-name">
                {{ userStore.userInfo.name }}
              </view>
              <view class="user-email">
                {{ userStore.userInfo.email }}
              </view>
            </view>
          </view>

          <view v-else class="no-user-info">
            暂无用户信息
          </view>
        </view>

        <!-- 用户信息表单 -->
        <view class="content-card">
          <view class="card-title">
            设置用户信息
          </view>

          <view class="form-group">
            <view class="form-item">
              <view class="form-label">
                用户名:
              </view>
              <wd-input v-model="userForm.name" placeholder="请输入用户名" />
            </view>

            <view class="form-item">
              <view class="form-label">
                邮箱:
              </view>
              <wd-input v-model="userForm.email" placeholder="请输入邮箱" />
            </view>

            <view class="button-grid">
              <wd-button type="primary" @click="saveUserInfo">
                保存信息
              </wd-button>
              <wd-button type="error" @click="userStore.clearUserInfo">
                清除信息
              </wd-button>
            </view>
          </view>
        </view>
      </view>
    </demo-block>

    <!-- 临时数据演示（不持久化） -->
    <demo-block title="非持久化演示 - 临时数据" transparent>
      <view class="info-box warning">
        <view class="info-title">
          ⚠️ 临时存储
        </view>
        <view class="info-body">
          这个 Store 的数据不会持久化，刷新页面后数据会丢失
        </view>
      </view>

      <view class="content-card">
        <view class="card-title">
          临时消息
        </view>

        <view v-if="tempStore.tempData.message" class="temp-message-display">
          <view class="message-content">
            {{ tempStore.tempData.message }}
          </view>
          <view class="timestamp">
            时间戳: {{ new Date(tempStore.tempData.timestamp).toLocaleString() }}
          </view>
        </view>

        <view v-else class="no-temp-message">
          暂无临时消息
        </view>

        <view class="form-group">
          <wd-input v-model="tempMessage" placeholder="请输入临时消息" />
          <view class="button-grid-small">
            <wd-button type="primary" size="small" @click="setTempMessage">
              设置消息
            </wd-button>
            <wd-button type="warning" size="small" @click="tempStore.clearMessage">
              清除消息
            </wd-button>
          </view>
        </view>
      </view>
    </demo-block>

    <!-- 持久化原理 -->
    <demo-block title="持久化实现原理" transparent>
      <view class="principles-container">
        <view class="content-card">
          <view class="card-title">
            持久化插件
          </view>
          <view class="card-description">
            项目使用自定义的 Pinia 插件实现持久化，位于
            <text class="code-inline">
              src/store/persist.ts
            </text>
          </view>
        </view>

        <view class="content-card">
          <view class="card-title">
            排除列表
          </view>
          <view class="card-description">
            可以通过排除列表控制哪些 Store 不需要持久化
          </view>

          <view
            class="code-block"
            @click="
              copyCode(`// 在 persist.ts 中配置排除列表
persist(context, ['global-register', 'temp'])`)
            "
          >
            <view class="code-content">
              <text>// 当前排除的 Store ID:</text>
              <text>['global-register', 'temp']</text>
            </view>
          </view>
        </view>

        <view class="content-card">
          <view class="card-title">
            使用说明
          </view>
          <view class="feature-list">
            <view>
              • <text class="feature-highlight green">
                自动持久化
              </text>：默认情况下，所有 Store 都会自动持久化
            </view>
            <view>
              • <text class="feature-highlight orange">
                排除机制
              </text>：通过 Store ID 控制哪些不需要持久化
            </view>
            <view>
              • <text class="feature-highlight blue">
                深拷贝保护
              </text>：使用深拷贝避免引用问题
            </view>
            <view>
              •
              <text class="feature-highlight purple">
                自动恢复
              </text>：页面刷新时自动从本地存储恢复数据
            </view>
          </view>
        </view>
      </view>
    </demo-block>

    <!-- 最佳实践 -->
    <demo-block title="最佳实践" transparent>
      <view class="best-practices-container">
        <view class="suggestion-card">
          <view class="suggestion-header">
            <view class="suggestion-icon">
              💡
            </view>
            <view class="suggestion-title">
              Store 设计建议
            </view>
          </view>
          <view class="suggestion-body">
            <view>• 使用组合式 API 风格定义 Store</view>
            <view>• 合理拆分 Store，避免单个 Store 过于庞大</view>
            <view>• 使用 TypeScript 获得更好的类型支持</view>
            <view>• 为 Store 提供清晰的命名和注释</view>
          </view>
        </view>

        <view class="suggestion-card">
          <view class="suggestion-header">
            <view class="suggestion-icon">
              🔒
            </view>
            <view class="suggestion-title">
              持久化建议
            </view>
          </view>
          <view class="suggestion-body">
            <view>• 敏感数据（如密码）不要持久化存储</view>
            <view>• 大量数据考虑使用数据库而非本地存储</view>
            <view>• 临时状态（如加载状态）不需要持久化</view>
            <view>• 定期清理无用的持久化数据</view>
          </view>
        </view>

        <view class="suggestion-card">
          <view class="suggestion-header">
            <view class="suggestion-icon">
              ⚡
            </view>
            <view class="suggestion-title">
              性能优化
            </view>
          </view>
          <view class="suggestion-body">
            <view>• 避免在 Store 中存储大量数据</view>
            <view>• 使用 computed 缓存复杂计算结果</view>
            <view>• 合理使用 $subscribe 监听状态变化</view>
            <view>• 考虑使用 $patch 批量更新状态</view>
          </view>
        </view>
      </view>
    </demo-block>

    <!-- 相关链接 -->
    <demo-block title="相关链接" transparent>
      <wd-cell-group border custom-class="related-links">
        <wd-cell
          title="📚 Pinia 官方文档"
          value="状态管理库"
          is-link
          @click="handleNavigate('https://pinia.vuejs.org/zh/')"
        />
        <wd-cell
          title="🎯 Vue 3 文档"
          value="组合式 API"
          is-link
          @click="handleNavigate('https://cn.vuejs.org/guide/extras/composition-api-faq.html')"
        />
        <wd-cell
          title="🔧 uni-app 存储"
          value="本地存储 API"
          is-link
          @click="handleNavigate('https://uniapp.dcloud.net.cn/api/storage/storage.html')"
        />
      </wd-cell-group>
    </demo-block>
  </view>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f3f4f6;
  padding: 12px 0;
  .dark & {
    background-color: var(--wot-dark-background);
  }
}

.header-card {
  margin: 0 12px 12px;
  .header-content {
    border-radius: 12px;
    background-color: #fff;
    padding: 32px 20px;
    text-align: center;
    .dark & {
      background-color: var(--wot-dark-background2);
    }
    .emoji {
      margin-bottom: 12px;
      font-size: 40px;
    }
    .title {
      margin-bottom: 8px;
      font-size: 24px;
      color: #1f2937;
      font-weight: bold;
      .dark & {
        color: var(--wot-dark-color);
      }
    }
    .subtitle {
      margin-bottom: 8px;
      font-size: 14px;
      color: #4b5563;
      line-height: 1.6;
      .dark & {
        color: var(--wot-dark-color2);
      }
    }
    .description {
      font-size: 12px;
      color: #6b7280;
      .dark & {
        color: var(--wot-dark-color2);
      }
    }
  }
}

.content-card {
  border-radius: 8px;
  background-color: #fff;
  padding: 16px;
  .dark & {
    background-color: var(--wot-dark-background2);
  }
}

.counter-display {
  margin-bottom: 16px;
  text-align: center;
  .count {
    margin-bottom: 8px;
    font-size: 32px;
    color: #3b82f6;
  }
  .double-count {
    font-size: 12px;
    color: #4b5563;
    .dark & {
      color: var(--wot-dark-color2);
    }
  }
}

.button-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

.button-grid-small {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.code-examples {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.code-block {
  border-radius: 4px;
  background-color: #f3f4f6;
  padding: 12px;
  .dark & {
    background-color: var(--wot-dark-background3);
  }
  .code-title {
    margin-bottom: 8px;
    font-size: 12px;
    color: #374151;
    font-weight: bold;
    .dark & {
      color: var(--wot-dark-color);
    }
  }
  .code-content {
    font-size: 10px;
    color: #4b5563;
    line-height: 1.6;
    font-family: monospace;
    .dark & {
      color: var(--wot-dark-color2);
    }
    text {
      display: block;
    }
  }
}

.info-box {
  margin-bottom: 12px;
  border-radius: 8px;
  padding: 12px;
  &.success {
    border: 1px solid #bbf7d0;
    background-color: #f0fdf4;
    .dark & {
      border-color: #22c55e;
      background-color: rgba(34, 197, 94, 0.2);
    }
    .info-title {
      color: #15803d;
      .dark & {
        color: #4ade80;
      }
    }
    .info-body {
      color: #16a34a;
      .dark & {
        color: #bbf7d0;
      }
    }
  }
  &.warning {
    border: 1px solid #fed7aa;
    background-color: #fff7ed;
    .dark & {
      border-color: #f97316;
      background-color: rgba(249, 115, 22, 0.2);
    }
    .info-title {
      color: #c2410c;
      .dark & {
        color: #fb923c;
      }
    }
    .info-body {
      color: #ea580c;
      .dark & {
        color: #fed7aa;
      }
    }
  }
  .info-title {
    margin-bottom: 4px;
    font-size: 14px;
    font-weight: bold;
  }
  .info-body {
    font-size: 12px;
    line-height: 1.6;
  }
}

.user-info-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card-title {
  margin-bottom: 12px;
  font-size: 16px;
  color: #1f2937;
  font-weight: bold;
  .dark & {
    color: var(--wot-dark-color);
  }
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  .avatar {
    border-radius: 9999px;
    font-size: 48px;
  }
  .user-details {
    flex: 1;
    .user-name {
      font-size: 16px;
      color: #1f2937;
      font-weight: bold;
      .dark & {
        color: var(--wot-dark-color);
      }
    }
    .user-email {
      font-size: 12px;
      color: #4b5563;
      .dark & {
        color: var(--wot-dark-color2);
      }
    }
  }
}

.no-user-info {
  text-align: center;
  color: #6b7280;
  .dark & {
    color: var(--wot-dark-color2);
  }
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-item {
  .form-label {
    margin-bottom: 4px;
    font-size: 12px;
    color: #374151;
    .dark & {
      color: var(--wot-dark-color);
    }
  }
}

.temp-message-display {
  margin-bottom: 16px;
  border-radius: 8px;
  background-color: #eff6ff;
  padding: 12px;
  .dark & {
    background-color: rgba(59, 130, 246, 0.2);
  }
  .message-content {
    font-size: 14px;
    color: #1d4ed8;
    font-weight: bold;
    .dark & {
      color: #93c5fd;
    }
  }
  .timestamp {
    font-size: 10px;
    color: #2563eb;
    .dark & {
      color: #bfdbfe;
    }
  }
}

.no-temp-message {
  margin-bottom: 16px;
  text-align: center;
  color: #6b7280;
  .dark & {
    color: var(--wot-dark-color2);
  }
}

.principles-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card-description {
  margin-bottom: 12px;
  font-size: 12px;
  color: #4b5563;
  line-height: 1.6;
  .dark & {
    color: var(--wot-dark-color2);
  }
}

.code-inline {
  color: #2563eb;
  font-family: monospace;
  .dark & {
    color: #60a5fa;
  }
}

.feature-list {
  font-size: 12px;
  color: #4b5563;
  line-height: 1.6;
  display: flex;
  flex-direction: column;
  gap: 8px;
  .dark & {
    color: var(--wot-dark-color2);
  }
  .feature-highlight {
    font-weight: bold;
    &.green {
      color: #16a34a;
      .dark & {
        color: #4ade80;
      }
    }
    &.orange {
      color: #ea580c;
      .dark & {
        color: #fb923c;
      }
    }
    &.blue {
      color: #2563eb;
      .dark & {
        color: #60a5fa;
      }
    }
    &.purple {
      color: #7e22ce;
      .dark & {
        color: #a78bfa;
      }
    }
  }
}

.best-practices-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.suggestion-card {
  border-radius: 8px;
  background-color: #fff;
  padding: 16px;
  .dark & {
    background-color: var(--wot-dark-background2);
  }
}

.suggestion-header {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  .suggestion-icon {
    margin-right: 8px;
    font-size: 24px;
  }
  .suggestion-title {
    font-size: 16px;
    color: #1f2937;
    font-weight: bold;
    .dark & {
      color: var(--wot-dark-color);
    }
  }
}

.suggestion-body {
  font-size: 12px;
  color: #4b5563;
  line-height: 1.6;
  display: flex;
  flex-direction: column;
  gap: 8px;
  .dark & {
    color: var(--wot-dark-color2);
  }
}

.related-links {
  border-radius: 8px !important;
  overflow: hidden;
}
</style>
